<?php

declare (strict_types=1);

namespace app\store\model;

use app\common\model\ExchangeCode as ExchangeCodeModel;
use fast\Random;


/**
 * 优惠券模型
 * Class Coupon
 * @package app\store\model
 */
class ExchangeCode extends ExchangeCodeModel
{
    /**
     * 获取列表记录
     * @param array $param
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(array $param = []): \think\Paginator
    {
        // 检索查询条件
        $filter = $this->getFilter($param);
        // 查询列表数据
        return $this->where($filter)
            ->where('exchange_id',$param['exchange_id'])
            ->order(['createtime' => 'desc'])
            ->paginate(15);
    }

    /**
     * 获取列表记录
     * @param array $param
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getListAll(array $param = []): array
    {
        // 检索查询条件
        $filter = $this->getFilter($param);
        $data = [];
        if(isset($param['page'])){
           $data = $this->where($filter)
                ->where('exchange_id',$param['exchange_id'])
                ->order(['createtime' => 'desc'])
                ->page($param['page'],10)
                ->select()
                ->toArray();
        }else{
           $data = $this->where($filter)
                ->where('exchange_id',$param['exchange_id'])
                ->order(['createtime' => 'desc'])
                ->select()
                ->toArray();
        }
        // 查询列表数据
        return $data;
    }

    /**
     * 检索查询条件
     * @param array $param
     * @return array
     */
    private function getFilter(array $param = []): array
    {
        // 默认查询条件
        $param = $this->setQueryDefaultValue($param, ['search' => '']);
        // 检索查询条件
        $filter = [];
        !empty($param['search']) && $filter[] = ['name', 'like', "%{$param['search']}%"];
        return $filter;
    }



    /**
     * 添加新记录
     * @param array $data
     * @return bool|false
     */
    public function add(array $data): bool
    {
        $exchangeModel = new \app\common\model\Exchange();
        $exchange = $exchangeModel->get($data['exchange_id']);
        if(!$exchange){
            return false;
        }
        for ($i=0;$i < $data['num'];$i++){
            $insertData[$i]['exchange_id'] = $data['exchange_id'];
            $insertData[$i]['store_id'] = self::$storeId;

            if($exchange->format === 10){
                $insertData[$i]['code'] = Random::alnum(12);
            }elseif($exchange->format === 20){
                $insertData[$i]['code'] = Random::numeric(12);
            }
            if($exchange->validity === 20){
                $insertData[$i]['start_time'] = $exchange->start_time;
                $insertData[$i]['end_time'] = $exchange->end_time;
            }elseif($exchange->validity === 30){
                $insertData[$i]['start_time'] = strtotime("+{$exchange->start_day} day");
                $insertData[$i]['end_time'] = strtotime("+{$exchange->end_day} day");
            }else{
                $insertData[$i]['start_time'] = time();
                $insertData[$i]['end_time'] = strtotime("+20 year");
            }
            $insertData[$i]['createtime'] = time();
        }
        $res = $this->insertAll($insertData);
        if($res){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     */
    public function edit(array $data): bool
    {
        return $this->save($this->createData($data)) !== false;
    }

    /**
     * 创建数据
     * @param array $data
     * @return array
     */
    private function createData(array $data): array
    {


//        // 折扣券记录有效期
//        // 领取后生效
//        if ($data['expire_type'] == ExpireTypeEnum::RECEIVE) {
//            $data['start_time'] = $data['end_time'] = 0;
//        } // 固定时间
//        elseif ($data['expire_type'] == ExpireTypeEnum::FIXED_TIME) {
//            $times = between_time($data['betweenTime']);
//            $data['start_time'] = $times['start_time'];
//            $data['end_time'] = $times['end_time'] + (86400 - 1);
//            $data['expire_day'] = 1;
//        }
//        // 适用范围
//        if ($data['apply_range'] == ApplyRangeEnum::ALL) {
//            $data['apply_range_config'] = [];
//        }
        return $data;
    }

    /**
     * 删除记录 (软删除)
     * @return bool
     */
    public function setDelete(): bool
    {
        return $this->save(['is_delete' => 1]) !== false;
    }

    /**
     * 删除多个兑换码
     * @return bool
     */
    public function deleteByIds(string $codeIds):bool
    {
        $codeIds = explode(',',$codeIds);
        $this->startTrans();
        try {
            foreach ($codeIds as $v){
                // 兑换码库详情
                $model = ExchangeCodeModel::detail((int)$v);
                $res = $model->delete();
                if(!$res){
                    $this->rollback();
                    return false;
                }
            }
            $this->commit();
            return true;
        }catch (\Exception $e){
            $this->rollback();
            return false;
        }
    }
}
